package cn.huobi.basic.service.impl;

import cn.huobi.basic.config.BussinessException;
import cn.huobi.basic.constant.BaseConstant;
import cn.huobi.basic.service.RegisterService;
import cn.huobi.basic.util.MD5Utils;
import cn.huobi.basic.util.StrUtils;
import cn.huobi.user.domain.Logininfo;
import cn.huobi.user.domain.User;
import cn.huobi.user.dto.EmailRegisterDto;
import cn.huobi.user.dto.PhoneRegisterDto;
import cn.huobi.user.mapper.LogininfoMapper;
import cn.huobi.user.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;

    /**
     * 手机号注册
     * @param phoneRegisterDto
     */
    @Override
    public void phoneRegister(PhoneRegisterDto phoneRegisterDto) {
        // 非空判断 注解判断
        // 参数校验
        this.verifyParam(phoneRegisterDto);
        /*
         * 将信息保存到logininfo 再保存到user
         */
        // 将PhoneRegisterDto 转换为 user
        User user = this.dtoConvertUser(phoneRegisterDto);
        // 将 user 转换为 logininfo
        Logininfo logininfo = this.userConvertLogininfo(user);
        // 添加
        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    /**
     * 邮箱注册
     */
    @Override
    public void emailRegister(EmailRegisterDto emailRegisterDto) {
        // 判断参数非空 注解
        // 参数校验
        this.verifyParam(emailRegisterDto);
        /*
         * 添加到数据库
         */
        // EmailRegisterDto 转换为 user
        User user = this.emailConvertUser(emailRegisterDto);
        // 将 user 转换为 logininfo
        Logininfo logininfo = this.userConvertLogininfo(user);
        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    /**
     * 校验邮箱账号注册参数
     */
    private void verifyParam(EmailRegisterDto emailRegisterDto) {
        /*
         * 判断邮箱账号是否被注册过
         */
        User user = userMapper.findBYEmail(emailRegisterDto.getEmail());
        if (user != null ){
            throw new BussinessException("该账号已被注册，请直接登录！");
        }
        /*
         * 判断验证码是否正确
         */
        String redisEmailCode = (String) redisTemplate.opsForValue().get(
                String.format(BaseConstant.VerfityCodeCons.REGISTER_EMAILCODE_EMAIL, emailRegisterDto.getEmail()));
        if (StringUtils.isBlank(redisEmailCode)){
            throw new BussinessException("验证码不正确！");
        }
        if (!redisEmailCode.equals(emailRegisterDto.getEmailCode())){
            throw new BussinessException("验证码不正确！");
        }
        /*
         * 判断两次密码是否一致
         */
        if (!emailRegisterDto.getPassword().equals(emailRegisterDto.getPasswordRepeat())){
            throw new BussinessException("两次密码不一致");
        }
    }

    /**
     * 将前端传递过来的 EmailRegisterDto 转换为 user
     */
    private User emailConvertUser(EmailRegisterDto dto){
        // 盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 密码
        String password = salt + dto.getPassword();
        // MD5加密
        String encryp = MD5Utils.encrypByMd5(password);
        return User.builder()
                .username(dto.getEmail())
                .email(dto.getEmail())
                .salt(salt)
                .password(encryp)
                .state(1)
                .createtime(new Date())
                .build();
    }


    /**
     * 将前端传递过来的 PhoneRegisterDto 转换为 user
     */
    private User dtoConvertUser(PhoneRegisterDto dto){
        // 盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 密码
        String password = salt + dto.getPassword();
        // MD5加密
        String encryp = MD5Utils.encrypByMd5(password);
        return User.builder()
                .username(dto.getPhone())
                .phone(dto.getPhone())
                .salt(salt)
                .password(encryp)
                .state(1)
                .createtime(new Date())
                .build();
    }

    /**
     * 将 user 转换为 logininfo
     */
    private Logininfo userConvertLogininfo(User user){
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        return logininfo;
    }

    /**
     * 手机号注册参数校验
     */
    private void verifyParam(PhoneRegisterDto phoneRegisterDto) {
        /*
         * 判断手机号/短信验证码是否正确
         */
        String redisSmsCode = (String) redisTemplate.opsForValue().get(
                String.format(BaseConstant.VerfityCodeCons.REGISTER_SMSCODE_PHONE, phoneRegisterDto.getPhone()));
        if (StringUtils.isBlank(redisSmsCode)){
            throw new BussinessException("短信验证码错误");
        }
        String[] split = redisSmsCode.split(":");
        String smsCode = split[0];
        if (!smsCode.equals(phoneRegisterDto.getSmsCode())){
            throw new BussinessException("短信验证码错误");
        }
        /*
         * 判断手机号是否注册过
         */
        User user = userMapper.findByPhone(phoneRegisterDto.getPhone());
        if (user != null){
            throw new BussinessException("该手机号已被注册，请直接登录");
        }
        /*
         * 判断两次密码是否一致
         */
        if (!phoneRegisterDto.getPassword().equals(phoneRegisterDto.getPasswordRepeat())){
            throw new BussinessException("两次密码不一致！");
        }
    }

}
